<template>
  <el-upload
    drag
    :action="url"
    :before-upload="beforeUploadHandle"
    :on-success="successHandle"
    :file-list="fileList"
    list-type="picture"
    :limit="1"
    style="text-align: center;"
    :on-remove="handleRemove"
  >
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <div class="el-upload__tip" slot="tip">
      只支持jpg、png、gif格式的图片！
    </div>
  </el-upload>
</template>

<script>
export default {
  data() {
    return {
      url: "",
      num: 0,
      successNum: 0,
      fileList: [],
      img: ""
    };
  },
  props: {
    value: String
  },
  methods: {
    init(img) {
      if (img != null) {
        this.img = img;
        let sp = this.img.split("/");
        let file = {
          url: this.img,
          fileName: sp[sp.length - 1]
        };
        if (this.img !== "") {
          this.fileList.push(file);
        }
      }

      this.url = this.$http.adornUrl(
        `/sys/oss/upload?token=${this.$cookie.get("token")}`
      );
    },
    clear() {
      this.fileList = [];
    },
    // 上传之前
    beforeUploadHandle(file) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error("只支持jpg、png、gif格式的图片！");
        return false;
      }
      this.num++;
    },
    // 上传成功
    successHandle(response, file, fileList) {
      this.fileList = fileList;
      this.successNum++;
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.$emit("input", response.url);
          this.$message.success(response.msg);
        }
      } else {
        this.$message.error(response.msg);
      }
    },
    handleRemove() {
      this.$emit("input", "");
    }
  }
};
</script>
